<template>
  <div>
    <van-nav-bar @click-left="$router.back()"
                 title="标题"
                 left-arrow>
    </van-nav-bar>
    <div class="item"
         v-for="item in comments"
         :key="item.id">
      <div class="head">
        <img src="../assets/img/3.png"
             alt />
        <div>
          <p>{{item.user.nickname}}</p>
          <span>{{new Date(item.create_date).toLocaleDateString()}}</span>
        </div>
        <span @click="replyFn(item.id)">回复</span>
      </div>
      <div class="text">{{item.content}}</div>
      <!-- 写嵌套评论 -->
      <CommentItem v-if="item.parent"
                   @reply="replyFn"
                   :obj='item.parent' />
      <!-- 写嵌套评论 -->
    </div>
    <!-- 底部评论块，需将文章详情数据传递给底部评论块组件 -->
    <CommentFooter ref="commentFooter"
                   @updateComment="updateCommentList"
                   :obj="artDetail" />
  </div>
</template>

<script>
import CommentFooter from '../components/CommentFooter.vue'
import CommentItem from '../components/CommentItem.vue'
import { post_comment, articleDetail } from '../api/news'
export default {
  components: { CommentFooter, CommentItem },
  created() {
    //   获取文章详情数据
    articleDetail(localStorage.getItem('artId')).then((res) => {
      this.artDetail = res.data.data
    })
    //   获取并保存评论列表数据
    post_comment(localStorage.getItem('artId')).then((res) => {
      this.comments = res.data.data
    })
  },
  data() {
    return {
      comments: [], //存放文章详情数据
      artDetail: {}, //评论列表数据
    }
  },
  methods: {
    //   回复评论
    replyFn(id) {
      // 1、调用底部评论块组件中的 showCommentBox函数，从而实现文本域等内容显示
      // 如何能够调用组件中 showCommentBox函数呢？答：可以先获取到该组件对象
      // 如何获取到该组件对象呢？答：通过ref属性获取
      this.$refs.commentFooter.showCommentBox()
      this.$refs.commentFooter.parent_id = id
    },
    //   刷新评论列表
    updateCommentList() {
      //   获取并保存评论列表数据
      post_comment(localStorage.getItem('artId')).then((res) => {
        this.comments = res.data.data
      })
    },
  },
}
</script>

<style lang="less" scoped>
/deep/.van-nav-bar {
  .van-icon {
    color: #000;
  }
}
.item {
  padding: 10px 10px;
  border-bottom: 1px solid #ccc;
  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    > img {
      width: (50/360) * 100vw;
      height: (50/360) * 100vw;
      display: block;
      border-radius: 50%;
    }
    > div {
      flex: 1;
      display: flex;
      flex-direction: column;
      margin-left: 10px;
      > span {
        font-size: 12px;
        color: #999;
        line-height: 25px;
      }
    }
    > span {
      color: #999;
      font-size: 13px;
    }
  }
  .text {
    font-size: 14px;
    color: #333;
    padding: 20px 0 10px 0;
  }
}
</style>